package com.zyf.project.binaryproto.converter.impl;

import com.zyf.project.binaryproto.converter.DynamicValueConverter;
import utils.binary.impl.BytesSlice;
import utils.binary.io.BytesOutputBuffer;
import utils.io.NumberMask;

/**
 * @author Zhou Yifan
 */
public abstract class AbstractNumberEncodingConverter implements DynamicValueConverter {

    private NumberMask numberMask;

    private Class<?> valueType;

    protected AbstractNumberEncodingConverter(NumberMask numberMask, Class<?> valueType) {
        this.numberMask = numberMask;
        this.valueType = valueType;
    }

    @Override
    public Class<?> getValueType() {
        return valueType;
    }

    public NumberMask getNumberMask() {
        return numberMask;
    }

    @Override
    public int encode(Object value, BytesOutputBuffer buffer) {
        long number = encode(value);
        return numberMask.writeMask(number, buffer);
    }

    @Override
    public Object decode(BytesSlice dataSlice) {
        long value = numberMask.resolveMaskedNumber(dataSlice);
        return decode(value);
    }

    protected abstract long encode(Object value);

    protected abstract Object decode(long value);

}
